module RailsEnhancer
  class MethodRemover
    def initialize(methods_map, controller_file_path, controller_file_name)
      @methods_map = methods_map
      @controller_file_path = controller_file_path
      @controller_file_name = controller_file_name
    end

    def remove_all
      @methods_map.sort! { |x, y| y[:start_line] <=> x[:start_line] }
      @methods_map.each do |e|
        remove_lines(@controller_file_path, e[:start_line], e[:lines_count])
      end
    end

    private

    def remove_lines(filename, start, num)
      tmp = Tempfile.open("#{@controller_file_name}.rb") do |fp|
        File.foreach(filename) do |line|
          if $. >= start and num > 0
            num -= 1
          else
            fp.puts line
          end
        end
        fp
      end
      FileUtils.copy(tmp.path, filename)
      tmp.unlink
    end
  end
end